"use client"; import { useEffect } from "react"; import { useParams, useRouter } from "next/navigation"; import { useQuery } from "@tanstack/react-query"; import { workspaceApi } from "@/lib/api"; import { sortByPosition } from "@/lib/utils"; /** * Workspace landing: redirect to the first top-level page (by fractional * position), or create a "Home" page when the workspace is empty. * * The param may be the magic value `default` (the root page + the middleware * redirect both target /w/default) — no workspace has that id/slug, so it is * resolved to the user's first workspace from GET /workspaces. */ export default function WorkspaceIndexPage() { const params = useParams<{ workspace: string }>(); const slugOrId = params?.workspace ?? "default"; const router = useRouter(); const isDefault = slugOrId === "default"; // `default` → the user's first workspace (id order; the personal // workspace is created first at registration). const workspaces = useQuery({ queryKey: ["workspaces"], queryFn: () => workspaceApi.list(), enabled: isDefault, retry: false }); useEffect(() => { const first = workspaces.data?.[0]; if (isDefault && first) { router.replace(`/w/${first.id}`, { scroll: false }); } }, [isDefault, workspaces.data, router]); const workspace = useQuery({ queryKey: ["workspaces", slugOrId], queryFn: () => workspaceApi.get(slugOrId), // Skip the (always-404) lookup while resolving the `default` alias. enabled: slugOrId.length > 0 && !isDefault, retry: false }); const pages = useQuery({ queryKey: ["workspaces", slugOrId, "pages", "index"], queryFn: () => workspaceApi.pages(slugOrId, { parent: null, limit: 100 }), enabled: Boolean(workspace.data?.id), retry: false }); useEffect(() => { if (!workspace.data?.id) return; const wsId = workspace.data.id; const list = pages.data ? sortByPosition(pages.data) : []; if (list.length > 0) { router.replace(`/w/${slugOrId}/page/${list[0]?.id}`); return; } // Empty workspace → create the "Home" page (idempotent: we redirect // before the second call could create a duplicate because the query // revalidates with the new page on the next visit). let cancelled = false; workspaceApi .pages(wsId, { parent: null, limit: 5 }) .then(async (existing) => { if (existing.length > 0) { if (!cancelled) router.replace(`/w/${slugOrId}/page/${existing[0]?.id}`); return; } const home = await createHome(wsId); if (!cancelled && home) router.replace(`/w/${slugOrId}/page/${home.id}`); }) .catch(() => { /* login-expired or transient — middleware/refresh handles it */ }); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [workspace.data?.id, pages.data, slugOrId, router]); return (